package pl.iachoo.ctl.tabory.dao.ibatis.services.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.ibatis.sqlmap.client.SqlMapClient;

import pl.iachoo.ctl.tabory.dao.api.services.ICompositionService;
import pl.iachoo.ctl.tabory.dao.data.vo.CompositionVO;
import pl.iachoo.ctl.tabory.dao.ibatis.services.BaseDaoService;

public class CompositionDaoServiceImpl extends BaseDaoService implements
		ICompositionService {

	private final Logger logger = Logger
			.getLogger(CompositionDaoServiceImpl.class);

	private final static String MAPPER = "map-composition";
	private final static String SQL_SELECT_ALL = ".selectAllCompositions";
	private final static String SQL_SAVE = ".saveComposition";
	private final static String SQL_UPDATE = ".updateComposition";
	private final static String SQL_SELECT_COMPOSITION_ID = ".selectCompositionId";

	public CompositionDaoServiceImpl(SqlMapClient sqlMapClient) {
		super(sqlMapClient);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CompositionVO> getListAllCompositions() throws Exception {
		logger.debug("Getting all compositions");
		sqlMapClient.startTransaction();
		List<CompositionVO> list = sqlMapClient.queryForList(MAPPER
				+ SQL_SELECT_ALL);
		sqlMapClient.commitTransaction();
		logger.debug(list);
		return list;
	}

	@Override
	public CompositionVO getComposition(String internalId) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CompositionVO getComposition(Long id) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CompositionVO saveUpdateComposition(CompositionVO composition)
			throws Exception {
		logger.debug("Save/Update composition: " + composition);
		if (composition.getId() == null) {
			saveCompostion(composition);
		} else {
			updateComposition(composition);
		}
		return null;
	}

	private void updateComposition(CompositionVO composition) throws Exception {
		logger.debug("Update composition: " + composition);
		sqlMapClient.startTransaction();
		sqlMapClient.insert(MAPPER + SQL_UPDATE, composition);
		sqlMapClient.commitTransaction();
	}

	private void saveCompostion(CompositionVO composition) throws Exception {
		logger.debug("Save composition: " + composition);
		sqlMapClient.startTransaction();
		Long id = (Long) sqlMapClient.queryForObject(MAPPER
				+ SQL_SELECT_COMPOSITION_ID);
		composition.setId(id);
		sqlMapClient.update(MAPPER + SQL_SAVE, composition);
		sqlMapClient.commitTransaction();
	}

	@Override
	public void deleteComposition(CompositionVO composition) throws Exception {
		// TODO Auto-generated method stub

	}

}
